var express = require('express');
var router = express.Router();
var connection = require('../mysql')
const { packRes } = require("../utils/packRes");



// 查询message get请求 / 查询数据 带分页 参数 limit默认5,page默认1
router.get('/', function (req, res, next) {
    const { limit = 5, page = 1 } = req.query;
    const offset = (page - 1) * limit;

    connection.query('SELECT COUNT(*) as total FROM message', function (error, results, fields) {
        if (error) throw error;
        const total = results[0].total;
        connection.query('SELECT * FROM message LIMIT ?, ?', [offset, limit * 1], function (error, results, fields) {
            if (error) throw error;
            const count = results.length;
            const pages = Math.ceil(total / limit);
            res.status(200).send(packRes(200, { results, count, total, pages }));
            return;
        });
    });

});

// 插入数据  post请求
 
 
router.post('/add', function (req, res, next) {
    const { content, username, nickname, userid, like } = req.body;
    let time = new Date().toISOString().slice(0, 19).replace('T', ' ');
    connection.query('INSERT INTO message (time,content,userid, username, nickname,  `like`) VALUES (?, ?, ?, ?, ?, ?)', [time, content,  userid, username, nickname,  like], function (error, results, fields) {
        if (error) throw error;
        res.status(200).send(packRes(200, '评论添加成功'));
    });
});



// 根据传入id 删除数据 post请求
router.post('/delete', function (req, res, next) {
    const { id } = req.body;
    const sql = `DELETE FROM message WHERE id=${id}`;
    connection.query(sql, function (error, results, fields) {
        if (error) throw error;
        res.status(200).send(packRes(200, { results }));
    });
});








module.exports = router;